//
//  CCMRequestStatusCodePlugin.swift
//  CCMoney_swift
//
//  Created by JKHuang on 2018/11/27.
//  Copyright © 2018 JKHuang. All rights reserved.
//

import UIKit
import Moya
import Result
import SVProgressHUD

class CCMRequestStatusCodePlugin: PluginType {

    private let viewController = UIApplication.shared.keyWindow?.parentContainerViewController()
    
    func willSend(_ request: RequestType, target: TargetType) {
        UIApplication.shared.isNetworkActivityIndicatorVisible = true
    }
    
    func didReceive(_ result: Result<Moya.Response, MoyaError>, target: TargetType) {
        UIApplication.shared.isNetworkActivityIndicatorVisible = false
        
        switch result {
        case .failure(let moyaError):
            let response: Response? = moyaError.response
            let statusCode = response?.statusCode
            if statusCode == 401 || statusCode == 417 {
//                if !(viewController?.isKind(of: LJLoginHomeViewController.self) ?? false) {
//                    let loginHome = LJLoginHomeViewController()
//                    let nvc = LJBaseNavigationController(rootViewController: loginHome)
//                    viewController?.present(nvc, animated: true, completion: nil)
//                }
                if statusCode == 401 {
                    SVProgressHUD.showError(withStatus: "请先登录")
                }
                if statusCode == 417 {
                    SVProgressHUD.showError(withStatus: "您的账号已在别处登录，请重新登录")
                }
            }
            if statusCode == 500 {
                
                //                guard let data = response?.data else { return }
                //                print(String(data:data, encoding: .utf8) ?? "")
                SVProgressHUD.showError(withStatus: "服务器错误")
            }
        default:
            break
        }
    }
}
